<?php

namespace App\Admin\Actions\Grid;

use App\Http\Controllers\Api\NotifyController;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Models\WxOrder;
use App\Wen\Utils\OrderUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class OrderSupplyAction extends BatchAction
{
    /**
     * @return string
     */
    protected $title = '批量补单';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $ids = $this->getKey();
        $supply_ids = [];
        foreach ($ids as $id){
            $WxOrder = WxOrder::find($id);
            if($WxOrder->order_state == 1){
                continue;
            }

            WxOrder::where('id', $id)->update(['order_state' => 1]);
            $type = $WxOrder->order_type;
            $uid = $WxOrder->user_id;
            $order_price = $WxOrder->order_price;
            // 开会员
            if ($type == 1) {
                $vip_options = json_decode(Settings::get('app_vip_options', '[]'), true);
                if(_empty_($vip_options)){
                    continue;
                }
                $flag = false;
                $days = 0;
                $coins = 0;
                foreach ($vip_options as $option){
                    if($option && $option['price'] == $order_price){
                        $flag = true;
                        $days = $option['days'];
                        $coins = $option['coins'];
                        break;
                    }
                }
                if($flag){
                    WxUserRepositores::vip($uid, $days);
                    if($coins > 0){
                        UserUtils::update_user_coins($uid,13, $coins, '开通'.$days.'天会员，赠送您'.Settings::get('app_coin_name', '硬币').'+'.$coins);
                    }
                }

            }
            // 充电
            if ($type == 2) {
                OrderUtils::exceptional($WxOrder);
            }
            if ($type == 3) {
                UserUtils::update_user_financial($uid, 6, $order_price, '充值了'.$order_price.'余额');
            }
            $supply_ids[] = $id;
        }

        return $this->response()
            ->success('如下订单补单成功'.json_encode($supply_ids))
            ->refresh();
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return ['确认补单?'];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [];
    }
}
